<template>
  <el-form class="query-container" ref="queryFormRef" :model="queryParams" :inline="true" @submit.native.prevent>
    <el-form-item label="车辆品牌" prop="brandInfo">
      <el-input
          v-model="queryParams.brandInfo"
          clearable
          placeholder="请输入车辆品牌"
          @keyup.enter.native="handleQuery"
      />
    </el-form-item>
    <el-form-item label="车牌号" prop="plateNumber">
      <el-input
          v-model="queryParams.plateNumber"
          clearable
          placeholder="请输入车牌号"
          @keyup.enter.native="handleQuery"
      />
    </el-form-item>
    <el-form-item label="车辆所属城市" prop="cityId">
      <el-input
          v-model="queryParams.cityId"
          clearable
          placeholder="请输入城市"
          @keyup.enter.native="handleQuery"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="handleQuery">搜索</el-button>
      <el-button @click="resetQuery">重置</el-button>
    </el-form-item>
  </el-form>

  <div class="inner-container">
    <el-row :gutter="10" style="margin-bottom:8px">
      <el-col :span="1.5">
        <el-button type="primary" plain @click="showAddDialog">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain @click="showEditDialog" :disabled="selectedIds.length!==1">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain @click="handleDelete(null)" :disabled="!selectedIds.length">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain @click="handleExport">导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="vehicleTableData" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50"/>

      <el-table-column prop="brandId" label="车辆品牌"/>
      <el-table-column prop="brandInfo" label="品牌信息"/>
      <el-table-column prop="plateNumber" label="车牌号" show-overflow-tooltip/>
      <el-table-column prop="score" label="车辆评分" show-overflow-tooltip/>
      <el-table-column prop="powerType" label="能源类型" show-overflow-tooltip/>
      <el-table-column prop="imgs" label="车辆图片" show-overflow-tooltip/>
      <el-table-column label="车辆图片">
        <template #default="scope">
          <el-button type="primary" link icon="View" @click="showImg(scope.row.imgs)">查看</el-button>

        </template>
      </el-table-column>
      <el-table-column prop="cityId" label="所属城市" show-overflow-tooltip/>
      <el-table-column prop="rentType" label="租用类型" show-overflow-tooltip/>
      <el-table-column prop="year" label="车龄" show-overflow-tooltip/>
      <el-table-column prop="transmissionType" label="档位类型" show-overflow-tooltip/>
      <el-table-column prop="vehicleTag" label="车辆标签" show-overflow-tooltip/>
      <el-table-column prop="dayRentPrice" label="日租金额" show-overflow-tooltip/>
      <el-table-column prop="monthRentPrice" label="月租金额" show-overflow-tooltip/>
      <el-table-column prop="vehicleEvaluationOne" label="评价1" show-overflow-tooltip/>
      <el-table-column prop="vehicleEvaluationTwo" label="评价2" show-overflow-tooltip/>
      <el-table-column prop="vehicleStatus" label="车辆状态">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 0" type="success">空闲</el-tag>
          <el-tag v-else-if="scope.row.status === 1" type="info">租用</el-tag>
          <el-tag v-else-if="scope.row.status === 2" type="info">维修</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip/>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="scope">
          <el-button type="primary" link icon="Edit" @click="showEditDialog(scope.row)">修改</el-button>
          <el-button type="primary" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <br>
    <el-pagination
        :total="total"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
    <el-dialog v-model="thumbnailDialog" title="修改封面图" style="width: 700px;">
      <el-row>
        <el-col :span="24">
          <img :src="thumbnailTemp" alt="" style="width: 100%"/>

          <el-upload
              v-model:file-list="thumbnailTempList"
              action=""
              :http-request="uploadFileThumbnail"
              :on-remove="handleRemove"
              :limit="1"
          >
            <el-button type="primary">重新上传</el-button>
          </el-upload>
        </el-col>
      </el-row>

    </el-dialog>

    <el-dialog v-model="imgUploadDialogVisible" title="图片上传">
      <!--  图片上传开始  -->
      <el-upload
          v-model:file-list="fileList"
          style="margin: 0;padding: 0"
          action=""
          multiple
          limit=9
          list-type="picture-card"
          :http-request="uploadFile"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"

      >
        <el-button type="primary">upload</el-button>
      </el-upload>

      <el-dialog v-model="imgDialogVisible" append-to-body>
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
      <!--  图片上传结束  -->
    </el-dialog>
    <el-dialog v-model="imgEditDialogVisible" title="图片修改" style="width: 700px; height: 500px">
<!--      <img style="width: 100%; height: 100%" src="d:/files/2024/07/18/952aa5b4-92c8-44da-9f0d-6e518f3bec3c.jpg" alt="">-->

      <el-row :gutter="10">
        <el-col v-for="img in allImgUrls" :span="6">
          <img :src="img" alt="" style="width: 100%">
          <el-button type="primary" @click="delImgUrl(img)">删除</el-button>
        </el-col>
      </el-row>
    </el-dialog>


    <el-dialog v-model="dialogVisible" :title="dialogTitle" :before-close="closeDialog" >
      <el-form ref="dialogFormRef" :model="formData" :rules="formRules" label-width="90px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="品牌信息" prop="brandInfo">
              <el-input v-model="formData.brandInfo" placeholder="请输入车辆品牌信息"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车辆品牌" prop="brandId">
              <el-select v-model="formData.brandId" placeholder="请输入品牌">
                <el-option v-for="item in brandArr" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车辆牌号" prop="plateNumber">
              <el-input v-model="formData.plateNumber" placeholder="请输入车牌号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车龄" prop="year">
              <el-input v-model="formData.year" placeholder="请输入车龄"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="车辆类型" prop="vehicleType">
              <el-input v-model="formData.vehicleType" placeholder="请输入车辆类型"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属城市" prop="cityId">
              <el-select v-model="formData.cityId" placeholder="请输入车辆所属城市">
                <el-option v-for="item in cityArr" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="租用类型" prop="rentType">
              <el-select v-model="formData.rentType" placeholder="请输入">
                <el-option v-for="item in rentTypeArr" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>

            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="档位类型" prop="transmissionType">
              <el-select v-model="formData.transmissionType" placeholder="请输入">
                <el-option v-for="item in transmissionTypeArr" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>

            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="车牌封面图" >
              <el-button type="primary" @click="showThumbnailDialog">修改封面图</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车辆标签" prop="vehicleTag">
              <el-input v-model="formData.vehicleTag" placeholder="请输入车辆标签"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车辆评分" prop="score">
              <el-input v-model="formData.score" placeholder="请输入车辆评分"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="日租金额" prop="dayRentPrice">
              <el-input v-model="formData.dayRentPrice" placeholder="请输入日租金额"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月租金额" prop="monthRentPrice">
              <el-input v-model="formData.monthRentPrice" placeholder="请输入月租金额"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="车辆图片">
              <el-button type="primary" @click="uploadImg()">上传图片</el-button>
              <el-button type="primary" @click="editImg()">修改图片</el-button>
            </el-form-item>

          </el-col>
        </el-row>
        <el-form-item label="车辆状态" prop="vehicleStatus">
          <el-radio-group v-model="formData.vehicleStatus">
            <el-radio v-for="item in vehicleStatusArr" :key="item.value" :label="item.label" :value="item.value"/>

          </el-radio-group>
        </el-form-item>
        <el-form-item label="车辆评价1" prop="vehicleEvaluationOne">
          <el-input v-model="formData.vehicleEvaluationOne" placeholder="请输入" type="textarea" :rows="2"/>
        </el-form-item>
        <el-form-item label="车辆评价2" prop="vehicleEvaluationTwo">
          <el-input v-model="formData.vehicleEvaluationTwo" placeholder="请输入" type="textarea" :rows="2"/>
        </el-form-item>

        <el-form-item label="能源类型">
          <el-select v-model="formData.powerType" placeholder="请选择车辆类型">
            <el-option v-for="item in powerTypeArr" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>

        <!-- 根据车辆类型动态显示特性 -->
        <el-row v-if="formData.powerType == 0">
          <el-col :span="6">
          <el-form-item label="电力">
            <el-select v-model="formData.vehicleFeature.feature1.electricType" default-first-option>
              <el-option v-for="item in electricTypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="驱动方式">
              <el-select v-model="formData.vehicleFeature.feature1.driveType">
                <el-option v-for="item in drivingModeArr" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="续航里程">
              <el-input v-model="formData.vehicleFeature.feature1.expectRange"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="formData.powerType == 1 || formData.powerType == 2">
          <el-col :span="6">
            <el-form-item label="排量">
              <el-input v-model="formData.vehicleFeature.feature1.displacement"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="驱动方式">
              <el-select v-model="formData.vehicleFeature.feature1.driveType">
                <el-option v-for="item in drivingModeArr" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="油箱容量">
              <el-input v-model="formData.vehicleFeature.feature1.tankCapacity"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="汽油">
              <el-select v-model="formData.vehicleFeature.feature1.gasType">
                <el-option v-for="item in gasTypeArr" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="4">
            <el-form-item label="座椅">
              <el-input v-model="formData.vehicleFeature.feature1.seats"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="倒车影像">
              <el-checkbox v-model="formData.vehicleFeature.feature2.rearViewCamera"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="天窗">
              <el-checkbox v-model="formData.vehicleFeature.feature2.sunroof"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="真皮座椅">
              <el-checkbox v-model="formData.vehicleFeature.feature2.leatherSeats"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="行李箱容量">
              <el-input v-model="formData.vehicleFeature.feature2.trunkCapacity"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="车载蓝牙">
              <el-checkbox v-model="formData.vehicleFeature.feature2.bluetooth"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="全景天窗">
              <el-checkbox v-model="formData.vehicleFeature.feature2.wholeSunRoof"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="行车记录仪">
              <el-checkbox v-model="formData.vehicleFeature.feature2.tachograph"></el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="导航仪">
              <el-checkbox v-model="formData.vehicleFeature.feature2.navigator"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="demo-date-picker">
              <div class="block">
                <span>可用时间</span>
                <el-date-picker
                    v-model="pickTime"
                    type="daterange"
                    range-separator="To"
                    start-placeholder="Start date"
                    end-placeholder="End date"
                    size="large"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                    @change="addAvailableTime(pickTime)"
                />
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <el-table :data="formData.availableTime"  height="200" scrollbar-always-on>
              <el-table-column  fixed label="时间段">
                <template #default="scope">
                  <span>{{scope.row.period.split(',')[0]}} 到 {{scope.row.period.split(',')[1]}}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="scope">
                  <el-button type="danger" link @click="deleteTimePeriod(scope.row.period) ">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>

        </el-row>



        <el-form-item label="菜单权限" prop="menuIds">
          <el-tree
              ref="menuTreeRef"
              :data="menuList"
              node-key="id"
              show-checkbox
              @check="handleMenuTreeCheck"
              :default-expanded-keys="defaultExpandedKeys"
              :props="{label: 'name', children: 'children'}"
              style="width: 100%; border: 1px solid #dcdfe6; border-radius: 4px;"
          />
        </el-form-item>
      </el-form>
      <template #footer class="dialog-footer">
        <el-button type="primary" @click="saveNewVehicle">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog title="查看图片" v-model="imagDialogVisible" width="800" >
      <img alt="" :src="imgUrl" style="width: 700px; margin: 0 auto; display: block"/>

    </el-dialog>
  </div>


</template>

<script setup>

import {computed, nextTick, onMounted, reactive, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import ElIconPicker from '@/components/ElIconPicker'
import request from '@/utils/request'
import { Plus } from '@element-plus/icons-vue'
import store from "@/store";


//图片上传开始
const imgUploadDialogVisible =ref(false)
let fileList = ref([])
const dialogImageUrl = ref('')
const imgDialogVisible = ref(false)
const imgEditDialogVisible = ref(false)
const thumbnailDialog =ref(false)
const thumbnailTemp =ref('')
let thumbnailTempList =ref([])

const handleRemove = (uploadFile, uploadFiles) => {


}
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  imgDialogVisible.value = true
}

const uploadImg=()=>{
  imgUploadDialogVisible.value=true
}


function uploadFile(file){

  const formData = new FormData()
  formData.append('file',file.file)
  request({
    url: '/file/upload',
    method:'post',
    data: formData
  }).then(res => {

    file.onSuccess(res.data)

  })
}
function uploadFileThumbnail(file){
  const formData = new FormData()
  formData.append('file',file.file)
  request({
    url: '/file/upload',
    method:'post',
    data: formData
  }).then(res => {
    thumbnailTempList.value=[]
    file.onSuccess(res.data)
    thumbnailTemp.value=res.data
  })

}

let allImgUrls= ref([])

const editImg =()=>{
  let imgUrls = []
  // console.log(formData.imgUrls)
  for (let file of fileList.value){
    imgUrls.push(file.response)
}
  // console.log(imgUrls)
  allImgUrls.value = imgUrls.concat(formData.imgUrls)
  // console.log(allImgUrls)
  imgEditDialogVisible.value=true
}

const delImgUrl = (url)=>{
  let found = false;
  if(fileList.value.length>0){
    for(let index in fileList.value){
      if(url === fileList.value[index].response){
        // console.log(parseInt(index))
        fileList.value.splice(parseInt(index),1)

        //标记找到
        found=true
        break
      }
    }
  }
  if(found===false && formData.imgUrls.length>0){

    for(let index in formData.imgUrls){
      if(url === formData.imgUrls[index]){
        formData.imgUrls.splice(parseInt(index),1)
        found=true
        break
      }
    }
  }
  if(found === true){
    ElMessage.success("删除成功")
    //获得更新后的图片地址数组
    allImgUrls.value=[]
    let imgUrls = []
    for (let file of fileList.value){
      imgUrls.push(file.response)
    }
    if(formData.imgUrls!=='' && formData.imgUrls!==undefined){
      allImgUrls.value = imgUrls.concat(formData.imgUrls)
    }
  }
}

const showThumbnailDialog = ()=>{
  thumbnailDialog.value=true;
}
//图片上传结束

//车辆配置----------------------------------



// 车辆信息列表 --------------------------------------------------

const loading = ref(false)
const queryFormRef = ref()
const queryParams = ref({pageNum: 1, pageSize: 10})
const total = ref(0)
const vehicleTableData = ref([])
const selectedIds = ref([])

const getVehicleInfo = () => {
  loading.value = true
  request.get('/api/bus/vehicle', {
    params: queryParams.value
  }).then(res => {
    total.value = res.data.total
    vehicleTableData.value = res.data.list
    loading.value = false
  })
}
getVehicleInfo();

//---------------------------------------------
const listData = () => {
  loading.value = true
  request.get('/api/bus/vehicle', {
    params: queryParams.value
  }).then(res => {
    total.value = res.data.total
    vehicleTableData.value = res.data.list
    loading.value = false

  })
}
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const handleQuery = () => {
  queryParams.value.pageNum = 1
  listData()
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  listData()
}

const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  listData()
}
const showEditDialog = (row) => {
  let id = row.id || selectedIds.value
  request.get(`/api/bus/vehicle/${id}`)
      .then(res => {

        const { data } = res;
        // 将vehicleFeature从字符串转换为对象
        const vehicleFeatureObj = JSON.parse(data.vehicleFeature);
        // const feature1Obj =  JSON.parse(vehicleFeatureObj.feature1);
        // const feature2Obj =  JSON.parse(vehicleFeatureObj.feature2);

        const availableTimeObj = JSON.parse(data.availableTime)
        // 使用Object.assign将数据赋值给formData，除了vehicleFeature
        let imgUrlArr=ref([])
        try {
          const imgUrlsObj = JSON.parse(data.imgUrls)
          imgUrlArr = imgUrlsObj.toString().split(',')
        }catch (e) {
          ElMessage.success("json error")
        }
        Object.assign(formData, {
          ...data,
          vehicleFeature: vehicleFeatureObj,

          availableTime: availableTimeObj,
          imgUrls : imgUrlArr
        });

        dialogTitle.value = '修改车辆详情';
        dialogVisible.value = true;

        allImgUrls.value = formData.imgUrls

        thumbnailTemp.value=formData.imgs

      })
}

const vehicleList = ref([])

const getVehicleList = () => {
  request.get(`/api/bus/vehicle/all`)
      .then(res => {
        vehicleList.value = res.data
      })
}


const handleDelete = (row) => {
  let ids = row ? [row.id] : [...selectedIds.value]
  if (ids.length === 0) {
    ElMessage.error('请选择要删除的记录')
    return
  }
  ElMessageBox.confirm('确定删除吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.delete(`/api/bus/vehicle?ids=${ids}`)
        .then(res => {
          selectedIds.value.length = 0
          listData()
          ElMessage.success('删除成功')
        })
  }).catch(() => {})
}
// 新增车辆表单--------------------------------------------------
const dialogTitle = ref('')
const dialogVisible = ref(false)
const dialogFormRef = ref()
const imagDialogVisible = ref(false)
const imgUrl= ref('')
const formData = reactive({
  id:undefined,
  brandInfo: undefined,
  brandId: undefined,
  plateNumber: undefined,
  score: undefined,
  imgs: undefined,
  year: undefined,
  cityId: undefined,
  rentType: undefined,
  vehicleTag:undefined,
  transmissionType: undefined,
  dayRentPrice: undefined,
  monthRentPrice: undefined,
  vehicleEvaluationOne: undefined,
  vehicleEvaluationTwo: undefined,
  availableTime : ref([]),
  vehicleFeature: {
    feature1: {
      displacement: '',
      seats: '',
      driveType: '',
      tankCapacity: '',
      gasType: '',
      expectRange : '',
      electricType : ''
    },
    feature2: {
      rearViewCamera: false,
      sunroof: false,
      leatherSeats: false,
      bluetooth : false,
      wholeSunRoof : false,
      tachograph : false,
      navigator : false,
      trunkCapacity: ''
    }

  },
  vehicleType : undefined,
  vehicleStatus : undefined,
  powerType : undefined,
  imgUrls : ''

})

const resetFormData = () => {
  for (const key in formData) {
    if (formData.hasOwnProperty(key) && key !== 'vehicleFeature' && key !== 'availableTime') {
      formData[key] = key === 'id' ? undefined : ''; // 根据字段特性重置，默认为 '' 或者保持特定字段如'id'为undefined
    }
  }
  // 如果vehicleFeature内部也有需要特别处理的字段，可以在这里添加逻辑
  // formData.vehicleFeature.feature1.displacement = ''
  // formData.vehicleFeature.feature1.seats = ''
  // formData.vehicleFeature.feature1.driveType = ''
  // formData.vehicleFeature.feature1.tankCapacity = ''
  // formData.vehicleFeature.feature1.gasType = ''
  // formData.vehicleFeature.feature1.expectRange = ''
  // formData.vehicleFeature.feature1.electricType = ''
  formData.vehicleFeature.feature1=ref({})
  formData.vehicleFeature.feature2.rearViewCamera = false
  formData.vehicleFeature.feature2.sunroof = false
  formData.vehicleFeature.feature2.leatherSeats = false
  formData.vehicleFeature.feature2.bluetooth = false;
  formData.vehicleFeature.feature2.wholeSunRoof = false
  formData.vehicleFeature.feature2.tachograph = false
  formData.vehicleFeature.feature2.navigator = false
  formData.vehicleFeature.feature2.trunkCapacity = ''


  formData.availableTime=[]
  pickTime.value=''

  fileList.value=[]
  allImgUrls.value=[]
  thumbnailTemp.value = ''
};

const showImg = (imgs)=>{
  imgUrl.value=imgs;
  imagDialogVisible.value=true;
}
const formRules = ref({
  brandId: [{required: true, message: '车辆品牌为必填项'}],
  plateNumber: [{required: true, message: '车牌号为必填项'}],
  brandInfo: [{required: true, message: '车辆信息为必填项'}]
})
const showAddDialog = () => {

  dialogTitle.value = '新增车辆'
  dialogVisible.value = true
}

const saveNewVehicle = () => {
  //获得更新后的图片地址数组
  allImgUrls.value=[]
  let imgUrls = []
  for (let file of fileList.value){
    imgUrls.push(file.response)
  }
  if(formData.imgUrls!=='' && formData.imgUrls!==undefined){
    allImgUrls.value = imgUrls.concat(formData.imgUrls)
  }



  const id = formData.id
  const temp = ref({})
  // temp.value.feature1 = formData.vehicleFeature.feature1;
  // temp.value.feature2 = formData.vehicleFeature.feature2;
  // temp.value.feature1 = JSON.stringify(formData.vehicleFeature.feature1);
  // temp.value.feature2 = JSON.stringify(formData.vehicleFeature.feature2);
  // formData.vehicleFeature.feature1 = JSON.stringify(formData.vehicleFeature.feature1);
  // formData.vehicleFeature.feature2 = JSON.stringify(formData.vehicleFeature.feature2);
  let serializedVehicleFeature = JSON.stringify(formData.vehicleFeature);

  const requestData = {
    ...formData, // 这里扩展formData除vehicleFeature之外的其他字段
    vehicleFeature: serializedVehicleFeature, // 替换formData中的vehicleFeature为序列化后的字符串
    availableTime: JSON.stringify(formData.availableTime),
    imgUrls : JSON.stringify(allImgUrls.value),
    imgs : thumbnailTemp.value

  };

  request({
    url: '/api/bus/vehicle',
    method: id ? 'put' : 'post',
    data: requestData
  }).then(res => {
    dialogVisible.value=false;
    getVehicleInfo();
    ElMessage.success(id ? '修改成功' : '新增成功')
    resetFormData();
  })

}
//退出弹窗提示-----------------------
const closeDialog =() => {

  if (confirm("确认退出吗?")){
    resetFormData();
    dialogVisible.value=false;




  }
}
//-------------------------------------------

//选择可用时间功能-----------------------------
const pickTime = ref('')


const addAvailableTime = (val)=>{
  const temp =ref({
    period : val.toString()
  })
  formData.availableTime.push(temp.value)


}

const deleteTimePeriod=(period)=>{
  formData.availableTime.forEach(function (item,index){

    if(item.period == period){
      formData.availableTime.splice(index,1);
    }
  })
}

//字典查询--------------------------------------------------------------
const drivingModeArr = ref([])
const gasTypeArr = ref([])
const powerTypeArr = ref([])
const cityArr = ref([])
const brandArr = ref([])
const rentTypeArr = ref([])
const transmissionTypeArr = ref([])
const vehicleStatusArr = ref([])
const vehicleSpecificationOptions = ref()
const electricTypeOptions = ref()

const selectDictOption =(arr, id)=> {
  const searchQuery = ref({dictId: id, pageNum:1, pageSize: 100})
  request.get('/api/sys/dict/options', {
    params: searchQuery.value
  }).then(res => {
    arr.value=res.data.list
  })
}
onMounted(() => {
  listData()
  selectDictOption(drivingModeArr,3)
  selectDictOption(gasTypeArr,4)
  selectDictOption(powerTypeArr,5)
  selectDictOption(cityArr, 6)
  selectDictOption(brandArr, 7)
  selectDictOption(rentTypeArr, 8)
  selectDictOption(transmissionTypeArr, 9)
  selectDictOption(vehicleStatusArr, 10)
  selectDictOption(vehicleSpecificationOptions,13)
  selectDictOption(electricTypeOptions, 15)




})

</script>

<style scoped>
.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 0 0 100px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
</style>
